	package com.agileai.em.module.expreimbursement.handler;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.common.AppConfig;
import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.em.common.ProcessHelper;
import com.agileai.em.cxmodule.BizCodeUtil;
import com.agileai.em.cxmodule.EmExpReimbursementManage;
import com.agileai.em.wsproxy.BizAttribute;
import com.agileai.em.wsproxy.DraftWorkItem;
import com.agileai.em.wsproxy.LaunchWorkItem;
import com.agileai.em.wsproxy.ProcessService;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.common.BeanFactory;
import com.agileai.hotweb.controller.core.StandardEditHandler;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.DateUtil;
import com.agileai.util.StringUtil;

public class EmExpReimbursementManageEditHandler
        extends StandardEditHandler {
	public static final String PROCESS_CODE = "Expreimbursement";
    public EmExpReimbursementManageEditHandler() {
        super();
        this.listHandlerClass = EmExpReimbursementManageListHandler.class;
        this.serviceId = buildServiceId(EmExpReimbursementManage.class);
    }
    public ViewRenderer prepareDisplay(DataParam param) {
		String operaType = param.get(OperaType.KEY);
		User user = (User) this.getUser();
		setAttribute("showCode", true);
		if(OperaType.CREATE.equals(operaType)){
			setAttribute("ER_PERSON", user.getUserId());
			setAttribute("ER_PERSON_NAME", user.getUserName());
			setAttribute("ER_DATE",DateUtil.getDate(DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL, new Date())));
			setAttribute("ER_MONEY", "0.00");
			setAttribute("showEdit",true);
			String invokeFrom = param.get("invokeFrom");
			setAttribute("invokeFrom", invokeFrom);
			setAttribute("showCode", false);
		}
		if (isReqRecordOperaType(operaType)){
			param.put("ER_ID",param.getString("BizId"));
			DataRow record = getService().getRecord(param);
			setAttribute("showFlow",true);
			if("UNSUBMITTED".equals(record.getString("ER_STATE"))){
				setAttribute("showEdit",true);
				setAttribute("showSubmit",true);
				setAttribute("showFlow",false);
			}
			String invokeFrom = param.get("invokeFrom");
			setAttribute("invokeFrom", invokeFrom);
			setAttributes(param);
			List<DataRow> records = getService().findApproveOpinionRecords(param);
			if(records.size()==0){
				setAttribute("hasAppRecords",false);
			}else{
				setAttribute("hasAppRecords",true);
				setAttribute("ApproceOpinionRecords", records);				
			}
			this.setAttributes(record);
		}
		this.setOperaType(operaType);
		processPageAttributes(param);
		return new LocalRenderer(getPage());
	}
    
    protected void processPageAttributes(DataParam param) {
        setAttribute("ER_STYLE",FormSelectFactory.create("ER_STYLE")
        		.addSelectedValue(getAttributeValue("ER_STYLE","")));
        setAttribute("ER_STATE",FormSelectFactory.create("EM_STATE")
        		.addSelectedValue(getAttributeValue("ER_STATE","UNSUBMITTED")));
    }
    
    public ViewRenderer doQueryAction(DataParam param){
		return prepareDisplay(param);
	}
    
    @PageAction
    public ViewRenderer save(DataParam param)throws Exception{
		String operateType = param.get(OperaType.KEY);
		User user = (User) this.getUser();
		if (OperaType.CREATE.equals(operateType)){
			param.put("sdate",DateUtil.getDateByType(DateUtil.YYMMDD_SLANTING, new Date())+" 00:00:00");
			param.put("edate",DateUtil.getDateByType(DateUtil.YYMMDD_SLANTING, new Date())+" 23:59:59");
			List<DataRow> list = this.getService().findRecords(param);
			String bizCode = BizCodeUtil.create("ER", list, BizCodeUtil.withPrefix);
			param.put("ER_CODE",bizCode);
			getService().createRecord(param);
			ProcessHelper processHelper = ProcessHelper.instance();
	   		ProcessService processService = processHelper.getBPMService();
	   		String uuId = param.get("ER_ID");
	   		DraftWorkItem draftWorkItem = new DraftWorkItem();
	   		draftWorkItem.setProcessCode(PROCESS_CODE);
	   		draftWorkItem.setUserCode(user.getUserCode());
	   		draftWorkItem.setBizTitle(param.getString("ER_TITLE"));
	   		draftWorkItem.setBizRecordId(uuId);
	   		draftWorkItem.setBizRecordCode(param.getString("ER_CODE"));
	   		processService.saveDraft(draftWorkItem);
		}
		else if (OperaType.UPDATE.equals(operateType)){
			getService().updateRecord(param);	
		}
		param.put("operaType", "update");
		return prepareDisplay(param);
	}
    
    @PageAction
   	public ViewRenderer submit(DataParam param) throws Exception {
    	String responseText = FAIL;
    	try {
    		User user = (User)getUser();
       		param.put("ER_STATE", "AUDITING");
       		getService().updateRecord(param);
       		
       		List<BizAttribute> attributeList = new ArrayList<BizAttribute>();
       		BizAttribute bizAttribute = new BizAttribute();
       		bizAttribute.setCode("userId");
       		bizAttribute.setValue(user.getUserId());
       		BizAttribute bizAttribute1 = new BizAttribute();
       		bizAttribute1.setCode("userCode");
       		bizAttribute1.setValue(user.getUserCode());
       		String title = param.get("ER_TITLE");
       		BizAttribute bizAttribute2 = new BizAttribute();
       		bizAttribute2.setCode("bizTitle");
       		bizAttribute2.setValue(title);
       		attributeList.add(bizAttribute);
       		attributeList.add(bizAttribute1);
       		String bizRecordId = param.get("ER_ID");
       		String bizRecordCode = param.get("ER_CODE");
       		if(StringUtil.isNullOrEmpty(bizRecordId)){
       			bizRecordId = KeyGenerator.instance().genKey();
       		}
       		ProcessHelper processHelper = ProcessHelper.instance();
       		ProcessService processService = processHelper.getBPMService();
       		String processId = processService.getCurrentProcessId(PROCESS_CODE);
       		LaunchWorkItem launchWorkItem = processHelper.createLaunchWorkItem(processId);
       		launchWorkItem.getAttributeList().addAll(attributeList);
       		launchWorkItem.setTitle(title);
       		launchWorkItem.setBizRecordId(bizRecordId);
       		launchWorkItem.setUserCode(user.getUserCode());
       		launchWorkItem.setBizRecordCode(bizRecordCode);
       		param.put("SKIP_FIRST_NODE", "true");
       		boolean skipFirstNode = "true".equals(param.get("SKIP_FIRST_NODE"));
       		processService.launchProcess(launchWorkItem,skipFirstNode);
       		String invokeFrom = param.get("invokeFrom");
       		if(StringUtil.isNotNullNotEmpty(invokeFrom)){
       			responseText = "fromBPM";
       		}else{
       			responseText = SUCCESS;
       		}
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
   		return new AjaxRenderer(responseText);
   	}
    
    @PageAction
	public ViewRenderer retrieveIds(DataParam param) throws JSONException{
		String responseText = "";
		try {
			AppConfig appConfig = BeanFactory.instance().getAppConfig();
	   		String BpmShowFlowUrl = appConfig.getConfig("GlobalConfig", "BpmShowFlowUrl");
			ProcessHelper processHelper = ProcessHelper.instance();
			ProcessService bpmService = processHelper.getBPMService();
			String bizRecordId = param.getString("ER_ID");
			List<String> aa = bpmService.getProcessId8InstId(PROCESS_CODE, bizRecordId);
			JSONObject jsonObject = new JSONObject();  
	        jsonObject.put("processId", aa.get(0));
	        jsonObject.put("processInstId", aa.get(1));
	        jsonObject.put("BpmShowFlowUrl", BpmShowFlowUrl);
	        String json = jsonObject.toString();
			responseText=json;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
    
    protected EmExpReimbursementManage getService() {
        return (EmExpReimbursementManage) this.lookupService(this.getServiceId());
    }
}
